package com.butang;



import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

/**
 * @Author weizs
 * @Create 2023/6/7 16:13
 * @Version 1.0
 */
public class OldScada {



    //十六位二进制最大数值
    static int HexBinary_Max = 65535;
    static long DoubleHexBinary_Max = 4294967295L;
    public static void main(String[] args) {
        try {
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn=  DriverManager.getConnection("jdbc:mysql://localhost:3306/scada","root","root");
            PreparedStatement pstmt= conn.prepareStatement("select * from meta_tag");
            Statement statement = conn.createStatement();
            PreparedStatement preparedStatement = null;
            String updateSql="update meta_tag_data_analysis  set TimeStamp= ?,TagValue= ? where TagID=?";
            preparedStatement = conn.prepareStatement(updateSql);

            long start = System.currentTimeMillis();
            String sql=null;
            ResultSet rs=null;
            //magData最新时间大于记录时间
//            if(timeStamp.after(recordTime)){
                System.out.println("------------------------开始解析:");
                sql="select a.TagID,a.TagName,a.miniMum,a.maxiMum,b.TagValue,a.Address,a.Description from meta_tag a inner join meta_tag_real_data b on a.Address=b.Address";
                rs = statement.executeQuery(sql);
                while(rs.next()){
                    int TagID=rs.getInt("TagID");
                    long miniMum = rs.getInt("miniMum");
                    long maxiMum = rs.getInt("maxiMum");
                    long TagValue = rs.getLong("TagValue");
                    String description =rs.getString("Description");
                    String TagName=rs.getString("TagName");
                    String Address=rs.getString("Address");
                    System.out.println(TagID+","+miniMum+","+maxiMum+","+TagValue+","+description+","+Address+","+TagName);
                    String Value="0";
                    String str=null;
                    String two=null;
                    float value1=0;

                    //取出Address下标进行判断
                    int length = Address.length();
                    if(length >= 3){
                        str = Address.substring(length-3, length);
                        //System.out.println("字符串后三位："+str);
                    }
                    two=Address.substring(2,3);
                    //System.out.println("字符串第二位："+two);

                    //系统故障状态和定日镜运行状态转换为16位二进制
                    if(two.equals("3") && (str.equals("001") || str.equals("002")) ){
                        Value = OldScada.decimalToBinary(TagValue);
                    }

                    //判断无符号转换为有符号十进制
                    if(miniMum==1){
                        if(description.equals("16")){
                            //value1 = DataAnalysisUtil.unsignedToSigned1(TagValue);
                            if(maxiMum>0){
//                                value1= value1 / maxiMum;
//                                Value= String.valueOf(value1);
                                Value= String.valueOf(TagValue / maxiMum);
                                System.out.println("--------16进制转换--------："+Value);
                            }
                        }if(description.equals("32")){
                            //value1 = DataAnalysisUtil.unsignedToSigned(TagValue);
                            if(maxiMum>0){
//                                value1= value1/ maxiMum;
//                                Value= String.valueOf(value1);
                                Value= String.valueOf(TagValue / maxiMum);
                                System.out.println("---------32进制转换-------："+Value);
                            }
                        }
                    }
                    if(maxiMum>0&&miniMum!=1){
                        Value= String.valueOf(TagValue / maxiMum);
                    }
//

//                        Calendar calendar= Calendar.getInstance();
//                        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
//                        String TimeStamp = dateFormat.format(calendar.getTime());

                        //数据量大时，localdatetime效率更高
                    LocalDateTime localDateTime = LocalDateTime.now();
                    DateTimeFormatter dateFormat=  DateTimeFormatter.ofPattern("yyyy-MM-dd :hh:mm:ss");
                    String TimeStamp = localDateTime.format(dateFormat);

                        preparedStatement.setString(1,TimeStamp);
                        preparedStatement.setString(2,Value);
                        preparedStatement.setInt(3,TagID);



                        //preparedStatement.executeUpdate();

                        //把data存储到容器中，然后一次性插入
                        preparedStatement.addBatch();

                        System.out.println(preparedStatement);
//                    }
//                    else{
//                        //解析完成 插入analysis表
//                        Calendar calendar= Calendar.getInstance();
//                        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
//                        String TimeStamp = dateFormat.format(calendar.getTime());
//                        String saveSql="insert into meta_tag_data_analysis  values( ?, ?, ?)";
//                        PreparedStatement preparedStatement = conn.prepareStatement(saveSql);
//                        preparedStatement.setInt(1,TagID);
//                        preparedStatement.setString(2,TimeStamp);
//                        preparedStatement.setString(3,Value);
//                        preparedStatement.executeUpdate();
//                        System.out.println(preparedStatement);
//                    }

                }
//                //插入最新记录时间
//                String saveTime="insert into meta_tag_history_time  values(?,?)";
//                PreparedStatement pstt = conn.prepareStatement(saveTime,Statement.RETURN_GENERATED_KEYS);
//                pstt.setInt(1,0);
//                pstt.setTimestamp(2,timeStamp);
//                pstt.executeUpdate();
//                ResultSet rst = pstt.getGeneratedKeys();
//                if (rst.next()) {
//                    int id = rst.getInt(1);
//                    System.out.println("--------------------------生成的id是："+id);
//                }
//                System.out.println("插入最新记录时间"+pstt);
//            }else{
//                System.out.println("---------不需要解析:");
//            }

            int[] temp = preparedStatement.executeBatch();
            System.out.println(Arrays.toString(temp));

            System.out.println("耗时:"+(System.currentTimeMillis() - start)+"ms");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        //这个只是测试
        //System.out.println(Integer.toBinaryString(100));
        //System.out.println(test1.decimalToBinary(25088));
        //System.out.println(test1.unsignedToSigned1(65535));
    }

    //Long.MAX_VALUE

    //十进制转换为十六位二进制并自动补齐
    public static String decimalToBinary(long n) {

        if (n < 0 || n >  HexBinary_Max) {
            throw new IllegalArgumentException("The input number must be between 0 and 65535.");
        }
        String binary = Long.toBinaryString(n);
        while (binary.length() < 16) {
            binary = "0" + binary;
        }
        return binary;
    }

    //十进制转换为三十二位二进制并自动补齐
    public static String decimalToBinary1(long n) {

        if (n < 0 || n >  DoubleHexBinary_Max) {
            throw new IllegalArgumentException("The input number must be between 0 and 65535.");
        }
        String binary = Long.toBinaryString(n);
        while (binary.length() < 32) {
            binary = "0" + binary;
        }
        return binary;
    }


    //无符号32位十进制转换为有符号十进制
    public static long unsignedToSigned(long unsigned) {
        if (unsigned <= 2147483647) {
            return unsigned;
        } else {
            return -(DoubleHexBinary_Max + 1 - unsigned);
        }
    }

    //无符号十六位十进制转换为有符号十进制

    public static long unsignedToSigned1(long unsigned) {
        if (unsigned <= 65535/2) {
            return unsigned;
        } else {
            return -(HexBinary_Max + 1 - unsigned);
        }
    }
}